﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using System.ServiceModel.DomainServices.Client;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;


namespace Rio.Framework.Pages.ChildWindows
{
    public partial class GroupFilterWindow : GroupWindowBase
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupFilterWindow" /> class.
        /// </summary>
        public GroupFilterWindow()
            : base()
        {
            Initialize();
        }

        /// <summary>
        /// Handles the Loaded event of the GroupFilterWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void GroupFilterWindow_Loaded(object sender, RoutedEventArgs e)
        {
            GetGroupList();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupFilterWindow" /> class.
        /// </summary>
        /// <param name="p_sGroupList">The P_S group list.</param>
        /// <param name="p_bGroupRestrict">The P_B group restrict.</param>
        public GroupFilterWindow(string p_sGroupList, bool p_bGroupRestrict = false)
            : base(p_sGroupList, p_bGroupRestrict)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupFilterWindow" /> class.
        /// </summary>
        /// <param name="p_oGroupList">The p_o group list.</param>
        /// <param name="p_bGroupRestrict">The P_B group restrict.</param>
        public GroupFilterWindow(List<Group> p_oGroupList, bool p_bGroupRestrict = false)
            : base(p_oGroupList, p_bGroupRestrict)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupFilterWindow" /> class.
        /// </summary>
        /// <param name="p_oGroupIdList">The p_o group id list.</param>
        /// <param name="p_bGroupRestrict">The P_B group restrict.</param>
        public GroupFilterWindow(List<long> p_oGroupIdList, bool p_bGroupRestrict = false)
            : base(p_oGroupIdList, p_bGroupRestrict)
        {
            Initialize();
        }


        /// <summary>
        /// Inits this instance.
        /// </summary>
        private void Initialize()
        {
            InitializeComponent();
            
            InitLabel();
            
            this.Loaded += GroupFilterWindow_Loaded;
            this.TextBoxStartingWith.Focus();
        }

        private void InitLabel()
        {
            LabelStartingWith.Text = Resx.GetLabel(ResxGroupFilterWindow.STARTING_WITH);
        }

        /// <summary>
        /// Handles the TextChanged event of the FilterValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs" /> instance containing the event data.</param>
        private void FilterValue_TextChanged(object sender, TextChangedEventArgs e)
        {
            List<Group> l_oGroupList = new List<Group>(FilterItems(TextBoxStartingWith.Text));
            List<Group> l_oAddedGroup = new List<Group>();
            foreach (Group l_ogrp in GridViewMessages.SelectedItems)
            {
                if (!l_oGroupList.Contains(l_ogrp))
                {
                    l_oGroupList.Add(l_ogrp);

                }
                l_oAddedGroup.Add(l_ogrp);
            }
           

            GridViewMessages.ItemsSource = l_oGroupList;

            foreach (Group l_oAddedGrp2 in l_oAddedGroup)
            {
                GridViewMessages.SelectedItems.Add(l_oAddedGrp2);
            }

            this.TextBoxStartingWith.Focus();
        }


        #region Selected listbox item event

        /// <summary>
        /// This method Get the group list and bind it to the grid
        /// </summary>
        /// <returns>
        /// A list of group
        /// </returns>
        private List<Group> GetGroupList()
        {
            GridViewMessages.IsBusy = true;

            BusinessEntitiesDomainContext l_oBEDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            var GroupList_Query = l_oBEDomainContext.GetAllGroupQuery();
            l_oBEDomainContext.Load(GroupList_Query, OnGetGroupListQueryCallback, null);
            this.IsEnabled = false;
            return null;
        }

        /// <summary>
        /// Call back method binding the list of group to the Grid
        /// </summary>
        /// <param name="result">List of group</param>
        public void OnGetGroupListQueryCallback(LoadOperation<Group> result)
        {
            this.IsEnabled = true;
            List<Group> l_oGroups = new List<Group>(result.Entities);
            if ((l_oGroups != null) && (l_oGroups.Count > 0))
            {
                //Init values list
                m_oGroupList = l_oGroups;
                String[] l_oGroupString = m_sGroupListToString.Split(new char[] { ';' });
                List<Group> l_oMailTo = new List<Group>();

                //Get the group based on the Mailto group name
                foreach (string str in l_oGroupString)
                {
                    foreach (Group l_oGroup in l_oGroups)
                    {
                        if (l_oGroup.Name.Equals(str))
                        {
                            l_oMailTo.Add(l_oGroup);
                        }
                    }
                }

                if (_groupRestrict)
                {
                    _displayedGroupList = l_oMailTo;
                }
                else
                {
                    _displayedGroupList = l_oGroups;
                }

                GridViewMessages.ItemsSource = _displayedGroupList;

                GridViewMessages.UnselectAll();

                if (!String.IsNullOrWhiteSpace(m_sGroupListToString))
                {
                    //Check the selected group based on the Mailto group name
                    foreach (string str in l_oGroupString)
                    {
                        foreach (Group l_oGroup in GridViewMessages.Items)
                        {
                            if (l_oGroup.Name.Equals(str))
                            {
                                GridViewMessages.SelectedItems.Add(l_oGroup);
                                break;
                            }
                        }
                    }
                }
                else if (_groupListId != null && _groupListId.Count > 0)
                {
                    foreach (long id in _groupListId)
                    {
                        foreach (Group l_oGroup in GridViewMessages.Items)
                        {
                            if (l_oGroup.Identifier == id)
                            {
                                GridViewMessages.SelectedItems.Add(l_oGroup);
                                break;
                            }
                        }
                    }
                }
            }

            GridViewMessages.IsBusy = false;
            GridViewMessages.Focus();
        }

        /// <summary>
        /// This event is called by the "OK" button 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetGroupItemButton_Click(object sender, RoutedEventArgs e)
        {
            if (GridViewMessages.SelectedItems != null)
            {
                m_szSelectedItems = new List<Group>();

                foreach (Group l_oGroup in GridViewMessages.SelectedItems)
                {
                    m_szSelectedItems.Add(l_oGroup);
                }

                this.DialogResult = true;
                this.Close();
            }
        }

        private void chkSelectAll_Checked(object sender, RoutedEventArgs e)
        {
            GridViewMessages.SelectAll();
        }

        private void chkSelectAll_Unchecked(object sender, RoutedEventArgs e)
        {
            GridViewMessages.UnselectAll();
        }


        /// <summary>
        /// Gets or sets the input value.
        /// </summary>
        /// <value>The input value.</value>
        public override string InputValue
        {
            get
            {
                if (GridViewMessages.SelectedItems != null && GridViewMessages.SelectedItems.Count > 0)
                {
                    string L_szSelectedGroups = String.Empty;
                    foreach (Group item in GridViewMessages.SelectedItems)
                    {
                        if (L_szSelectedGroups.Equals(String.Empty))
                        {
                            L_szSelectedGroups = item.Name;
                        }
                        else
                        {
                            L_szSelectedGroups = L_szSelectedGroups + ";" + item.Name;
                        }
                    }

                    return L_szSelectedGroups;
                }
                else
                {
                    return String.Empty;
                }

            }
            set
            {

                GridViewMessages.UnselectAll();
                String[] L_oGroups = m_sGroupListToString.Split(new char[] { ';' });

                foreach (string str in L_oGroups)
                {
                    foreach (Group l_oGroup in GridViewMessages.Items)
                    {
                        if (l_oGroup.Name.Equals(str))
                        {
                            GridViewMessages.SelectedItems.Add(l_oGroup);
                        }
                    }
                }

            }
        }
        #endregion

        /// <summary>
        /// Handles the Click event of the SetGroupItemCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void SetGroupItemCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
}
